const mongoose = require('mongoose');
const Friend = require('../models/friend');
const User = require('../models/user');


// 添加好友
exports.add = async (ctx, next) => {
    const { from, to } = ctx.request.fields;
    await new Promise((resolve, reject) => {
        
        Friend.findOne({'$or': [{ from, to }, { from: to, to: from }]}, function(err, data) {
            if (err) {
                reject(err);
            } else if (data) {
                resolve(302);
            } else {
                const friend = new Friend({from, to});
                friend.save(function(err, data) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(200);
                    }
                })
            }
        })
        
    }).then(data => {
        if (data === 200) {
            ctx.body = {
                reasonCode: 200,
                message: '添加好友成功'
            }
        } else if (data === 302) {
            ctx.body = {
                reasonCode: 302,
                message: '两人已经是好友了，不用重新添加'
            }
        }
    }).catch(err => {
        ctx.body = err;
    })
}


// 好友列表
exports.list = async (ctx, next) => {
    const { id } = ctx.request.query;
    await new Promise((resolve, reject) => {
        let users = {};
        User.find({}, function(err, data) {
            if (err) {
                reject(err);
            }
            data.forEach(item => {
                users[item._id] = {
                    name: item.name,
                    avatar: item.avatar,
                    desc: item.desc,
                    id: item._id
                }
            })
            Friend.find({'$or': [{ from: id }, { to: id }]}, function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    let list = new Set();
                    data.forEach(item => {
                        list.add(users[item.to]);
                        list.add(users[item.from]);
                    })
                    resolve([...list]);
                }
            })
        })
        
    }).then(data => {
        ctx.body = {
            reasonCode: 200,
            users: data
        }
    }).catch(err => {
        ctx.body = err;
    })
}